package org.hh.netty.server;

import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.NodeOrientation;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import lombok.SneakyThrows;
import org.hh.netty.entity.Message;
import org.hh.netty.entity.User;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Teacher数据模型对象
 */
public class TeacherModel {

    @FXML
    VBox vBox;                                           //消息vbox
    ListView userList;                                   //用户列表vbox
    List<User> onlineUsers = new ArrayList<User>();         //在线用户列表
    ObservableList<User> userObservableList;
    private static TeacherModel teacherModel = new TeacherModel();

    public ObservableList<User> getUserObservableList() {
        return userObservableList;
    }

    public void setUserObservableList(ObservableList<User> userObservableList) {
        this.userObservableList = userObservableList;
    }

    public VBox getvBox() {
        return vBox;
    }

    public void setvBox(VBox vBox) {
        this.vBox = vBox;
    }

    public ListView getUserList() {
        return userList;
    }

    public void setUserList(ListView userList) {
        this.userList = userList;
    }

    private TeacherModel(){};

    public static TeacherModel getInstance(){
        return teacherModel;
    }

    /**
     * 添加消息
     * @param user
     * @param message
     */
    @SneakyThrows
    public void addMessage(User user, Message message){
        URL url = getClass().getClassLoader().getResource("fxml/msg.fxml");
        AnchorPane anchorPane = FXMLLoader.load(url);
        ObservableList<Node> children = anchorPane.getChildren();
        ImageView imageView = (ImageView) children.get(0);
        imageView.setImage(user.getImage());
        Label name = (Label) children.get(1);
        name.setText(user.getName() + " " + message.getLocalDateTimeString());
        Label msg = (Label) children.get(2);
        msg.setMaxWidth(600);
        msg.setText(message.getMsg());

        if (message.getType()==1) {
            msg.setTextFill(Color.web("blue"));
        }else if(message.getType()==3){
            anchorPane.setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT);
        }

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                vBox.getChildren().add(anchorPane);
            }
        });
    }
}
